package com.ruoyi.ade.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.ade.domain.AdeKnowledgeBase;
import com.ruoyi.ade.llm.model.AdeKnowledgeRetriveConfig;
import com.ruoyi.ade.llm.model.AdeRetrivedKnowledge;
import com.ruoyi.ade.llm.model.AdeRetrivedResponse;
import com.ruoyi.ade.llm.service.IAdeKnowledgeEmbedService;
import com.ruoyi.ade.mapper.AdeKnowledgeBaseMapper;
import com.ruoyi.ade.model.AdeKnowledgeRetriveRequest;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.ade.mapper.AdeKnowledgeCacheMapper;
import com.ruoyi.ade.domain.AdeKnowledgeCache;
import com.ruoyi.ade.service.IAdeKnowledgeCacheService;

/**
 * Ade Knowledge CacheService业务层处理
 * 
 * @author wxh
 * @date 2025-07-20
 */
@Service
public class AdeKnowledgeCacheServiceImpl implements IAdeKnowledgeCacheService 
{
    @Autowired
    private AdeKnowledgeCacheMapper adeKnowledgeCacheMapper;

    @Autowired
    private AdeKnowledgeBaseMapper adeKnowledgeBaseMapper;

    @Autowired
    private IAdeKnowledgeEmbedService adeKnowledgeEmbedService;
    /**
     * 检索知识   优先命中缓存（关系型数据库表）  否则检索索引数据库(Milvus)
     * @param emr
     * @param request
     * @return
     */
    public List<AdeRetrivedKnowledge> retrieveKnowledge(Long standardId, String emr, AdeKnowledgeRetriveRequest request){

        //优先从本库中检索     根据standard_id, adekb_id, chunktype检索
        AdeKnowledgeCache cond = new AdeKnowledgeCache();
        cond.setAdekbId(request.getAdekbid());
        cond.setStandardId(standardId);
        cond.setChunkType(request.getChunkType());
        List<AdeKnowledgeCache> caches = adeKnowledgeCacheMapper.selectAdeKnowledgeCacheList(cond);
        if(caches != null && caches.size() > 0){
            String ades = caches.get(0).getAdes();
            List<AdeRetrivedKnowledge> knowledges = JSONArray.parseArray(ades,AdeRetrivedKnowledge.class);
//            List<AdeRetrivedKnowledge> list = new ArrayList<>();
//            for(AdeRetrivedKnowledge k: knowledges){
//                if(k.getSimScore()>=request.getSimScoreThreshold()) list.add(k);
//            }
            return knowledges;
        }

        //数据库中没有查询到 则重新从索引库检索
        //确认emr不为空
        if(StringUtils.isEmpty(emr)){
            throw new RuntimeException("emr is empty");
        }
        //首先验证索引库是否存在
        AdeKnowledgeBase adeKnowledgeBase = adeKnowledgeBaseMapper.selectAdeKnowledgeBaseById(request.getAdekbid());
        if(adeKnowledgeBase == null || StringUtils.isEmpty(adeKnowledgeBase.getCollectionName())){
            throw new RuntimeException("No collection found for:" + request.getAdekbid());
        }
        //创建检索配置
        AdeKnowledgeRetriveConfig ragConfig = new AdeKnowledgeRetriveConfig();
        ragConfig.setCollection(adeKnowledgeBase.getCollectionName());
        ragConfig.setDebug(false);
        ragConfig.setChunkType(request.getChunkType());
        ragConfig.setEmbedModel(adeKnowledgeBase.getEmbedModel());
        //此处阈值默认为0.5
        ragConfig.setSimScoreThreshold(request.getSimScoreThreshold());

        ragConfig.setTopN(request.getTopN());

        List<AdeRetrivedKnowledge> knowledges = null;
        try {
            AdeRetrivedResponse resp = adeKnowledgeEmbedService.search(emr, ragConfig, null);
            knowledges = resp.getAdes();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("Milvus search error："+e.getMessage());
        }

        AdeKnowledgeCache cache = new AdeKnowledgeCache();
        cache.setStandardId(standardId);
        cache.setAdekbId(request.getAdekbid());
        cache.setChunkType(request.getChunkType());
        cache.setAdes(knowledges==null?"[]" :JSONArray.toJSONString(knowledges));
        adeKnowledgeCacheMapper.insertAdeKnowledgeCache( cache);

        return knowledges;
    }



    /**
     * 查询Ade Knowledge Cache
     * 
     * @param id Ade Knowledge Cache主键
     * @return Ade Knowledge Cache
     */
    @Override
    public AdeKnowledgeCache selectAdeKnowledgeCacheById(Long id)
    {
        return adeKnowledgeCacheMapper.selectAdeKnowledgeCacheById(id);
    }

    /**
     * 查询Ade Knowledge Cache列表
     * 
     * @param adeKnowledgeCache Ade Knowledge Cache
     * @return Ade Knowledge Cache
     */
    @Override
    public List<AdeKnowledgeCache> selectAdeKnowledgeCacheList(AdeKnowledgeCache adeKnowledgeCache)
    {
        return adeKnowledgeCacheMapper.selectAdeKnowledgeCacheList(adeKnowledgeCache);
    }

    /**
     * 新增Ade Knowledge Cache
     * 
     * @param adeKnowledgeCache Ade Knowledge Cache
     * @return 结果
     */
    @Override
    public int insertAdeKnowledgeCache(AdeKnowledgeCache adeKnowledgeCache)
    {
        adeKnowledgeCache.setCreateTime(DateUtils.getNowDate());
        return adeKnowledgeCacheMapper.insertAdeKnowledgeCache(adeKnowledgeCache);
    }

    /**
     * 修改Ade Knowledge Cache
     * 
     * @param adeKnowledgeCache Ade Knowledge Cache
     * @return 结果
     */
    @Override
    public int updateAdeKnowledgeCache(AdeKnowledgeCache adeKnowledgeCache)
    {
        return adeKnowledgeCacheMapper.updateAdeKnowledgeCache(adeKnowledgeCache);
    }

    /**
     * 批量删除Ade Knowledge Cache
     * 
     * @param ids 需要删除的Ade Knowledge Cache主键
     * @return 结果
     */
    @Override
    public int deleteAdeKnowledgeCacheByIds(Long[] ids)
    {
        return adeKnowledgeCacheMapper.deleteAdeKnowledgeCacheByIds(ids);
    }

    /**
     * 删除Ade Knowledge Cache信息
     * 
     * @param id Ade Knowledge Cache主键
     * @return 结果
     */
    @Override
    public int deleteAdeKnowledgeCacheById(Long id)
    {
        return adeKnowledgeCacheMapper.deleteAdeKnowledgeCacheById(id);
    }
}
